package com.cs252.flashcardz;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class AccessData {
	public int logCheck;
	public String results;

	public AccessData(){
		logCheck = 0;
		results = "";
	}
	
	public void setLogCheck(int val){
		logCheck = val;
	}
	
	public int login(final String user, final String pass){
		Thread login = new Thread(new Runnable() {
            public void run() {
            	String result = "";
				//http post
				try{
					
				//ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				//nameValuePairs.add(new BasicNameValuePair("sqlString","FlashCardz"));
				//Log.i("Name val", "Name: " + nameValuePairs.toString());
				        HttpClient httpclient = new DefaultHttpClient();
				        HttpPost httppost = new HttpPost("http://cking.webuda.com/getLogin.php");
				        //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				        HttpResponse response = httpclient.execute(httppost);
				        HttpEntity entity = response.getEntity();
				        InputStream is = entity.getContent();
				        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				        StringBuilder sb = new StringBuilder();
				        String line = null;
				        while ((line = reader.readLine()) != null) {
				                sb.append(line + "\n");
				        }
				        is.close();
				 
				        result=sb.toString();
				        results = result;
				        JSONArray jArray = new JSONArray(result);
				        for(int i=0;i<jArray.length();i++){
				                JSONObject json_data = jArray.getJSONObject(i);
				                Log.i("data" + i,"Username: "+json_data.getString("Username")+
				                        ", Password: "+json_data.getString("Password")
				                );
				                if(json_data.getString("Username").equals(user) && json_data.getString("Password").equals(pass)){
				                	setLogCheck(1);
				                	break;
				                }
				        }
				}catch(Exception e){
				        Log.e("log_tag", "Error in http connection "+e.toString());
				}
            }
        });
		login.start();
		try {
			login.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return logCheck;
	}
	
	public int signUp(final String user, final String pass){
		Thread signUp = new Thread(new Runnable() {
            public void run() {
            	String result = "";
				//http post
				try{
					
				//ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				//nameValuePairs.add(new BasicNameValuePair("sqlString","FlashCardz"));
				//Log.i("Name val", "Name: " + nameValuePairs.toString());
				        HttpClient httpclient = new DefaultHttpClient();
				        HttpPost httppost = new HttpPost("http://cking.webuda.com/getLogin.php");
				        //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				        HttpResponse response = httpclient.execute(httppost);
				        HttpEntity entity = response.getEntity();
				        InputStream is = entity.getContent();
				        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				        StringBuilder sb = new StringBuilder();
				        String line = null;
				        while ((line = reader.readLine()) != null) {
				                sb.append(line + "\n");
				        }
				        is.close();
				 
				        result=sb.toString();
				        JSONArray jArray = new JSONArray(result);
				        for(int i=0;i<jArray.length();i++){
				                JSONObject json_data = jArray.getJSONObject(i);
				                if(json_data.getString("Username").equals(user)){
				                	setLogCheck(1);
				                	break;
				                }
				        }
				        
				        if(logCheck == 0){
							ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
							nameValuePairs.add(new BasicNameValuePair("username", user));
							nameValuePairs.add(new BasicNameValuePair("password", pass));
							Log.i("Name val", "Name: " + nameValuePairs.toString());
							HttpClient httpclient2 = new DefaultHttpClient();
					        HttpPost httppost2 = new HttpPost("http://cking.webuda.com/signUp.php");
					        httppost2.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					        HttpResponse response2 = httpclient2.execute(httppost2);
					        
					        ArrayList<NameValuePair> nameValuePairs3 = new ArrayList<NameValuePair>();
							nameValuePairs3.add(new BasicNameValuePair("user", user));
							Log.i("Name val", "Name: " + nameValuePairs.toString());
							HttpClient httpclient3 = new DefaultHttpClient();
					        HttpPost httppost3 = new HttpPost("http://cking.webuda.com/Create_table_for_signUp.php");
					        httppost3.setEntity(new UrlEncodedFormEntity(nameValuePairs3));
					        HttpResponse response3 = httpclient3.execute(httppost3);
							
						}
				}catch(Exception e){
				        Log.e("log_tag", "Error in http connection "+e.toString());
				}
            }
        });
		signUp.start();
		try {
			signUp.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return logCheck;
	}

}
